package org.dfl.plugin.views.actions;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dfl.core.data.IODataManager;
import org.dfl.core.data.Token;
import org.dfl.core.model.Place;
import org.dfl.messages.Messages;
import org.dfl.plugin.ProjectConstraints;
import org.dfl.plugin.dialogs.DialogsManager;
import org.dfl.plugin.utils.WorkbenchUtil;
import org.dfl.plugin.views.debug.model.HistoryTreeElem;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.actions.ActionDelegate;

/**
 * action that provide saving token objects with their history. 
 * It's used in a HistoriesTreeView (see mapping in plugin.xml file)
 * @author Piotr Wlodarczyk
 *
 */
public class SaveTokensWithHistoriesAction extends ActionDelegate {

	private IStructuredSelection selection = StructuredSelection.EMPTY;

	/* (non-Javadoc)
	 * @see org.eclipse.ui.actions.ActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
	 */
	public void selectionChanged(IAction action, ISelection sel) {
		if(sel instanceof IStructuredSelection)
			selection = (IStructuredSelection) sel;
		else 
			selection = StructuredSelection.EMPTY;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.actions.ActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	@SuppressWarnings("unchecked") //$NON-NLS-1$
	public void run(IAction action) {
		if(selection.isEmpty()) return;
		if(selection instanceof IStructuredSelection){
			List<Token> tokens = new ArrayList<Token>();
			IStructuredSelection sel = (IStructuredSelection) selection;

			Place place = null;
			java.util.Iterator iter = sel.iterator();
			while(iter.hasNext()){
				Object selObj = iter.next();
				if(selObj instanceof HistoryTreeElem){
					tokens.addAll(((HistoryTreeElem)selObj).getTokens());
					place = ((HistoryTreeElem)selObj).getPlace();
				}
			}
			if(tokens.isEmpty()){
				DialogsManager.openErrorDialog(Messages.SaveTokensAction_1);
			}else{
				Map<String,Collection<Token>> tokensMap = new HashMap<String, Collection<Token>>();
				tokensMap.put(place.getId(),tokens);
				saveTokens(tokensMap);
			}
		}
	}

	private void saveTokens(Map<String,Collection<Token>> tokens) {
		FileDialog dlg = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE);
        
		IProject project = WorkbenchUtil.getCurrentProject();
		String projectPath = project.getLocation().toFile().getAbsolutePath();
		if(new File(projectPath + ProjectConstraints.PROJECT_DIR_HISTORIES).exists()){ //$NON-NLS-1$
			dlg.setFilterPath(projectPath + ProjectConstraints.PROJECT_DIR_HISTORIES); //$NON-NLS-1$
		}else{
			dlg.setFilterPath(projectPath);
		}
		
		IEditorPart editor = WorkbenchUtil.getActiveEditor();
		String prefix = editor.getEditorInput().getName().replace(".dfl", "")+"_h_"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
		prefix += String.format(Messages.FlowRunner_outputFileFormat,  new GregorianCalendar());
		
        // Change the title bar text
        dlg.setText(Messages.SaveTokensAction_2);
        dlg.setFileName(prefix+".xml");
		
     // null if user cancels
        String fileName = dlg.open();
        if (fileName != null) {
        	if(new File(fileName).exists() && !DialogsManager.openOkCancelDialog(Messages.SaveAllTokensAction_9,Messages.SaveAllTokensAction_10)){
        		return;
        	}
        	try {
        		IODataManager.saveTokens(fileName,tokens);
                WorkbenchUtil.refreshProject(project);
			} catch (Exception e) {
				DialogsManager.openErrorDialog(e);
			}
        }
	}
}
